use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde::Serialize;
use axum::body::Body;

/// 监控统计数据结构
#[derive(Debug, Serialize, Clone)]
pub struct MonitoringStats {
    pub total_requests: u64,
    pub successful_requests: u64,
    pub failed_requests: u64,
    pub average_response_time: f64,
    pub current_connections: u64,
    pub uptime_seconds: u64,
    pub memory_usage_mb: f64,
}

/// 请求统计计数器
#[derive(Debug)]
pub struct RequestStats {
    total_requests: AtomicU64,
    successful_requests: AtomicU64,
    failed_requests: AtomicU64,
    total_response_time: AtomicU64,
    request_count: AtomicU64,
    current_connections: AtomicU64,
    start_time: SystemTime,
}

impl RequestStats {
    pub fn new() -> Self {
        Self {
            total_requests: AtomicU64::new(0),
            successful_requests: AtomicU64::new(0),
            failed_requests: AtomicU64::new(0),
            total_response_time: AtomicU64::new(0),
            request_count: AtomicU64::new(0),
            current_connections: AtomicU64::new(0),
            start_time: SystemTime::now(),
        }
    }

    /// 记录请求开始
    pub fn record_request_start(&self) {
        self.total_requests.fetch_add(1, Ordering::Relaxed);
        self.current_connections.fetch_add(1, Ordering::Relaxed);
    }

    /// 记录请求完成
    pub fn record_request_complete(&self, success: bool, duration: Duration) {
        self.current_connections.fetch_sub(1, Ordering::Relaxed);
        
        if success {
            self.successful_requests.fetch_add(1, Ordering::Relaxed);
        } else {
            self.failed_requests.fetch_add(1, Ordering::Relaxed);
        }
        
        self.total_response_time.fetch_add(duration.as_millis() as u64, Ordering::Relaxed);
        self.request_count.fetch_add(1, Ordering::Relaxed);
    }

    /// 获取监控统计
    pub fn get_stats(&self) -> MonitoringStats {
        let total_requests = self.total_requests.load(Ordering::Relaxed);
        let successful_requests = self.successful_requests.load(Ordering::Relaxed);
        let failed_requests = self.failed_requests.load(Ordering::Relaxed);
        let total_response_time = self.total_response_time.load(Ordering::Relaxed);
        let request_count = self.request_count.load(Ordering::Relaxed);
        let current_connections = self.current_connections.load(Ordering::Relaxed);

        let average_response_time = if request_count > 0 {
            total_response_time as f64 / request_count as f64
        } else {
            0.0
        };

        let uptime_seconds = self.start_time.elapsed().unwrap_or(Duration::from_secs(0)).as_secs();
        
        // 模拟内存使用（实际项目中可以使用系统API获取真实内存使用）
        let memory_usage_mb = (std::process::id() as f64) / 1000.0; // 简单模拟

        MonitoringStats {
            total_requests,
            successful_requests,
            failed_requests,
            average_response_time,
            current_connections,
            uptime_seconds,
            memory_usage_mb,
        }
    }
}

/// 监控服务
#[derive(Debug, Clone)]
pub struct MonitoringService {
    pub stats: Arc<RequestStats>,
}

impl MonitoringService {
    pub fn new() -> Self {
        Self {
            stats: Arc::new(RequestStats::new()),
        }
    }

    /// 创建监控中间件
    pub fn create_middleware(&self) -> MonitoringMiddleware {
        MonitoringMiddleware {
            stats: self.stats.clone(),
        }
    }
}

/// 监控中间件
#[derive(Debug, Clone)]
pub struct MonitoringMiddleware {
    stats: Arc<RequestStats>,
}

impl MonitoringMiddleware {
    pub async fn monitor_request(
        &self,
        request: axum::http::Request<Body>,
        next: axum::middleware::Next,
    ) -> axum::response::Response {
        let start_time = SystemTime::now();
        
        // 记录请求开始
        self.stats.record_request_start();

        // 执行请求
        let response = next.run(request).await;

        // 计算请求耗时
        let duration = start_time.elapsed().unwrap_or(Duration::from_millis(0));
        
        // 判断请求是否成功（2xx状态码为成功）
        let success = response.status().is_success();
        
        // 记录请求完成
        self.stats.record_request_complete(success, duration);

        response
    }
}